package com.songlei.rtcadriondh265demo

import android.Manifest
import android.annotation.SuppressLint
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import android.widget.Button
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.PopupWindow
import android.widget.TextView
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import com.songlei.rtcadriondh265demo.rtc.WebRTCProxy
import com.songlei.rtcadriondh265demo.utils.CodecUtils
import com.songlei.rtcadriondh265demo.utils.NetInfoManager
import com.songlei.rtcadriondh265demo.utils.WebRTCStats
import org.webrtc.EglBase
import org.webrtc.RendererCommon
import org.webrtc.SurfaceViewRenderer

class MainActivity : ComponentActivity() {
    // 默认地址配置
    private val DEFAULT_PUSH_URL = "https://113.57.95.140:18094/index/api/webrtc?app=live&stream=test&type=push"
    private val DEFAULT_PLAY_URL = "webrtc://113.57.95.140:18094/index/api/webrtc?app=live&stream=test&type=play"

    private lateinit var pusherSurfaceViewRenderer: SurfaceViewRenderer
    private lateinit var playerSurfaceViewRenderer: SurfaceViewRenderer
    private lateinit var eglBase: EglBase

    private var pusherWebRtcProxy: WebRTCProxy? = null
    private var playerWebRtcProxy: WebRTCProxy? = null

    // UI组件
    private lateinit var etPushUrl: EditText
    private lateinit var etPlayUrl: EditText
    private lateinit var btnPush: Button
    private lateinit var btnPlay: Button
    // 状态变量
    private var isPushing = false
    private var isPlaying = false

    //codecs info
    private lateinit var btnCodecInfo: Button
    private var codecInfoPopup: PopupWindow? = null
    private var isCodecInfoShowing = false

    //网络信息显示 TextView
    private lateinit var tvPushNetInfo: TextView
    private lateinit var tvPlayNetInfo: TextView

    private lateinit var netInfoManager: NetInfoManager


    private val requiredPermissions = arrayOf(
        Manifest.permission.RECORD_AUDIO,
        Manifest.permission.CAMERA,
        Manifest.permission.INTERNET,
        Manifest.permission.ACCESS_NETWORK_STATE,
        Manifest.permission.ACCESS_WIFI_STATE
    )
    private val requestPermissionsLauncher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
            val allPermissionsGranted = permissions.entries.all { entry -> entry.value }
            if (!allPermissionsGranted) {
                //没有被允许就弹框说明
                Toast.makeText(this, "需要摄像头、录音、网络和网络状态权限", Toast.LENGTH_SHORT).show()
            }
        }
    private fun checkPermissions(): Boolean {
        return requiredPermissions.all { permission ->
            ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED
        }
    }
    private fun requestPermissions() {
        requestPermissionsLauncher.launch(requiredPermissions)
    }

    private fun toggleCodecInfo() {
        if (isCodecInfoShowing) {
            dismissCodecInfo()
        } else {
            showCodecInfo()
        }
        isCodecInfoShowing = !isCodecInfoShowing
    }

    private fun showCodecInfo() {
        val popupView = LayoutInflater.from(this).inflate(R.layout.dialog_codec_info, null)
        val tvInfo = popupView.findViewById<TextView>(R.id.tv_codec_info)
        // Get the close button
        val btnClose = popupView.findViewById<Button>(R.id.btn_close_codec_info)
        // Set click listener for the close button
        btnClose.setOnClickListener {
            dismissCodecInfo() // Close the popup when the button is clicked
        }

        // 设置文本内容
        tvInfo.text = CodecUtils.getFormattedCodecInfo()

        codecInfoPopup = PopupWindow(
            popupView,
            ViewGroup.LayoutParams.MATCH_PARENT, // 宽度
            ViewGroup.LayoutParams.WRAP_CONTENT, // 高度
            true
        ).apply {
            // 设置弹出窗口属性
            isOutsideTouchable = true
            elevation = 10f
            setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

            // 设置动画
            animationStyle = R.style.CodecInfoAnimation

            // 显示在顶部
            showAtLocation(
                window.decorView.findViewById(android.R.id.content),
                Gravity.TOP or Gravity.CENTER_HORIZONTAL,
                0,
                200 // 距离顶部的偏移量
            )
        }
    }

    private fun dismissCodecInfo() {
        codecInfoPopup?.dismiss()
        codecInfoPopup = null
        isCodecInfoShowing = false
    }

    @SuppressLint("CutPasteId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //=== 新增初始化 ===//
        netInfoManager = NetInfoManager(
            findViewById(R.id.tv_push_net_info),
            findViewById(R.id.tv_play_net_info)
        )

        if (!checkPermissions()) {
            requestPermissions()
        }
        //输出支持的编解器
        btnCodecInfo = findViewById(R.id.btn_codec_info)
        btnCodecInfo.setOnClickListener { toggleCodecInfo() }

        // 初始化WebRTC环境
        eglBase = EglBase.create()

        // 绑定视图组件
        etPushUrl = findViewById(R.id.et_push_url)
        etPlayUrl = findViewById(R.id.et_play_url)
        btnPush = findViewById(R.id.btn_push)
        btnPlay = findViewById(R.id.btn_play)

        //初始化网络信息显示 TextView
        tvPushNetInfo = findViewById(R.id.tv_push_net_info)
        tvPlayNetInfo = findViewById(R.id.tv_play_net_info)

        // 设置默认地址（新增代码）
        setupDefaultUrls()


        // 初始化SurfaceView
        pusherSurfaceViewRenderer = initSurfaceView(R.id.push_preview_container)
        playerSurfaceViewRenderer = initSurfaceView(R.id.play_preview_container)

        // 按钮点击监听
        btnPush.setOnClickListener { handlePush() }
        btnPlay.setOnClickListener { handlePlay() }

    }
    // 新增方法：配置默认地址
    private fun setupDefaultUrls() {
        // 推流地址配置
        etPushUrl.setText(DEFAULT_PUSH_URL)
        etPushUrl.setSelection(DEFAULT_PUSH_URL.length) // 光标定位到末尾

        // 拉流地址配置
        etPlayUrl.setText(DEFAULT_PLAY_URL)
        etPlayUrl.setSelection(DEFAULT_PLAY_URL.length)

    }

    private fun initSurfaceView(containerId: Int): SurfaceViewRenderer {
        return SurfaceViewRenderer(this).apply {
            // Step 1: 初始化渲染器
            try {
                init(eglBase.eglBaseContext, null)
            } catch (e: Exception) {
                Log.e("WebRTC", "SurfaceView初始化失败", e)
                return@apply
            }

            // Step 2: 配置渲染参数
            setScalingType(RendererCommon.ScalingType.SCALE_ASPECT_FIT)
            setEnableHardwareScaler(true)
            setMirror(isPushing)

            // Step 3: 安全添加视图
            val rootView = window.decorView.findViewById<View>(android.R.id.content)
            rootView.post {
                val container = rootView.findViewById<FrameLayout>(containerId) ?: run {
                    Log.e("WebRTC", "容器视图$containerId 不存在！")
                    return@post
                }

                if (parent != null) {
                    (parent as ViewGroup).removeView(this)
                }
                container.addView(this,0)

                // Step 4: 延迟调整尺寸
                //post {
                //    adjustSurfaceViewSize(this)
                //}
            }
        }
    }

    private fun adjustSurfaceViewSize(view: SurfaceViewRenderer) {
        val aspectRatio = 9f / 16f  // 根据实际视频比例修改
        view.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
            override fun onPreDraw(): Boolean {
                if (view.measuredWidth > 0) {
                    view.viewTreeObserver.removeOnPreDrawListener(this)
                    val targetWidth = view.measuredWidth
                    val targetHeight = (targetWidth * aspectRatio).toInt()
                    view.layoutParams = FrameLayout.LayoutParams(targetWidth, targetHeight).apply {
                        gravity = Gravity.CENTER
                    }
                    view.requestLayout()
                    Log.d("WebRTC", "视图尺寸已调整: ${targetWidth}x$targetHeight")
                }
                return true
            }
        })
    }

    // 修改后的处理函数
    private fun handlePush() {
        val pushUrl = correctUrl(etPushUrl.text.toString().trim())

        if (!isPushing) {
            // 开始推流逻辑
            if (!validateUrl(pushUrl)) {
                etPushUrl.error = "请输入有效的推流地址 (https:// 或 webrtc://)"
                return
            }
            if (startPushStream(pushUrl)) {
                isPushing = true
                btnPush.text = "停止推流"
                Log.d("WebRTC", "推流已启动")
            }
        } else {
            // 停止推流逻辑
            if (stopPushStream()) {
                isPushing = false
                btnPush.text = "推流"
                Log.d("WebRTC", "推流已停止")
            }
        }
    }

    private fun handlePlay() {
        val playUrl = correctUrl(etPlayUrl.text.toString().trim())

        if (!isPlaying) {
            // 开始拉流逻辑
            if (!validateUrl(playUrl)) {
                etPlayUrl.error = "请输入有效的拉流地址 (https:// 或 webrtc://)"
                return
            }
            if (startPlayStream(playUrl)) {
                isPlaying = true
                btnPlay.text = "停止拉流"
                Log.d("WebRTC", "拉流已启动")
            }
        } else {
            // 停止拉流逻辑
            if (stopPlayStream()) {
                isPlaying = false
                btnPlay.text = "拉流"
                Log.d("WebRTC", "拉流已停止")
            }
        }
    }

    // 新增流控制方法（需实现具体逻辑）
    private fun startPushStream(url: String): Boolean {
        if (pusherWebRtcProxy != null) {
            pusherWebRtcProxy!!.destroy()
        }
        pusherWebRtcProxy = WebRTCProxy(this@MainActivity).apply {
            create(
                eglBase = eglBase,
                surfaceViewRenderer = pusherSurfaceViewRenderer,
                isPublish = true,
                isShowCamera = true,
                playUrl = url,
                callBack = object : WebRTCProxy.WebRtcCallBack {
                    override fun onSuccess() {
                    }
                    override fun onFail() {                        // 失败处理
                    }
                },
                statsCallback = object : WebRTCProxy.StatsCallback {
                    override fun onStatsUpdated(stats: WebRTCStats) {
                        netInfoManager.updatePushStats(stats)
                    }
                }
            )

        }
        return true
    }

    private fun stopPushStream(): Boolean {
        if (pusherWebRtcProxy != null) {
            pusherWebRtcProxy!!.destroy()
            netInfoManager.clearPushStats()
        }
        return true
    }

    private fun startPlayStream(url: String): Boolean {
        if (playerWebRtcProxy != null) {
            playerWebRtcProxy!!.destroy()
        }
        playerWebRtcProxy = WebRTCProxy(this@MainActivity)
        playerWebRtcProxy!!.create(
            eglBase,
            playerSurfaceViewRenderer,
            isPublish = false,
            isShowCamera = true,
            playUrl = url,
            callBack = object : WebRTCProxy.WebRtcCallBack {
                override fun onSuccess() {}
                override fun onFail() {}
            },
            statsCallback = object : WebRTCProxy.StatsCallback {
                override fun onStatsUpdated(stats: WebRTCStats) {
                        netInfoManager.updatePlayStats(stats)
                }
            })
        return true
    }

    private fun stopPlayStream(): Boolean {
        if (playerWebRtcProxy != null) {
            playerWebRtcProxy!!.destroy()
            netInfoManager.clearPlayStats()
        }
        return true
    }

    private fun validateUrl(url: String): Boolean {
        return url.startsWith("http://")||
                url.startsWith("https://") ||
                url.startsWith("webrtc://")
    }
    private fun correctUrl(url: String): String {
        return if (url.startsWith("webrtc://")) "https://${url.substringAfter("webrtc://")}" else url
    }

    override fun onDestroy() {
        super.onDestroy()
        dismissCodecInfo()

        // 释放 WebRTC 相关资源
        pusherWebRtcProxy?.destroy()
        playerWebRtcProxy?.destroy()
        pusherWebRtcProxy = null
        playerWebRtcProxy = null

        // 释放 SurfaceView
        pusherSurfaceViewRenderer.release()
        playerSurfaceViewRenderer.release()
        eglBase.release()
    }

    // 扩展函数：布局监听
    private fun View.doOnLayout(action: (View) -> Unit) {
        viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                if (measuredWidth > 0 && measuredHeight > 0) {
                    viewTreeObserver.removeOnGlobalLayoutListener(this)
                    action(this@doOnLayout)
                }
            }
        })
    }


}

